package com.wx.service.impl;

import com.wx.constants.Constants;
import com.wx.entity.SysBanner;
import com.wx.exception.BusinessException;
import com.wx.mapper.SysBannerMapper;
import com.wx.properties.OssProperties;
import com.wx.service.SysBannerService;
import com.wx.utils.SnowFlakeUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>Title:	  weixin-go-with-you <br/> </p>
 * <p>Description TODO <br/> </p>
 * <p>Company:    医百科技有限公司  <br/> </p>
 *
 * @Author <a href="yangwensheng@100doc.com.cn"/>杨文生</a>  <br/>
 * @Date 2021/4/5 21:23
 */
@Service
public class SysBannerServiceImpl extends BaseServiceImpl<SysBanner> implements SysBannerService {

    @Resource
    private SysBannerMapper sysBannerMapper;

    @Resource
    private OssProperties ossProperties;

    @Override
    public int saveBanner(SysBanner sysBanner) {
        sysBanner.setId(SnowFlakeUtil.getStringId());
        sysBanner.setLinkUrl(ossProperties.getUrl() + sysBanner.getImgUrl());
        return sysBannerMapper.insertSelective(sysBanner);
    }

    @Override
    public int deleteById(String id, String userId, String realName) {
        SysBanner sysBanner = sysBannerMapper.selectByPrimaryKey(id);
        if(sysBanner == null){
            throw new BusinessException("参数不合法");
        }
        sysBanner.setDelFlag(Constants.DELETE_YES);
        sysBanner.setUpdateBy(userId);
        sysBanner.setUpdater(realName);
        sysBanner.setUpdateDate(new Date());
        return sysBannerMapper.updateByPrimaryKeySelective(sysBanner);
    }

    @Override
    public List<SysBanner> selectLastBanner() {
        List<SysBanner> sysBanners = sysBannerMapper.selectLastBanner();
        for (SysBanner sysBanner : sysBanners) {
            sysBanner.setImgUrl(ossProperties.getUrl() + sysBanner.getImgUrl());
        }
        return sysBanners;
    }

    @Override
    public List<SysBanner> listPage(SysBanner param) {
        List<SysBanner> sysBanners = sysBannerMapper.listPage(param);
        for (SysBanner sysBanner : sysBanners) {
            sysBanner.setImgUrl(ossProperties.getUrl() + sysBanner.getImgUrl());
        }
        return sysBanners;
    }

    @Override
    public int updateBanner(SysBanner sysBanner) {
        if(StringUtils.isEmpty(sysBanner.getImgUrl())){
            throw new BusinessException("url不能为空");
        }
        sysBanner.setLinkUrl(sysBanner.getImgUrl());
        sysBanner.setImgUrl(sysBanner.getImgUrl().replace(ossProperties.getUrl(),""));
        return sysBannerMapper.updateByPrimaryKeySelective(sysBanner);
    }
}
